package com.library.repository.impl;/*
 *@author lzg
 *@data 2020/11/18
 */

import com.library.entity.Book;
import com.library.entity.BookCase;
import com.library.repository.BookRepository;
import com.library.utils.JDBCTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class BookRepositoryImpl implements BookRepository {
    @Override
    public List<Book> findAll(int pageIndex, int limitNu) {
        //连接数据库获取数据
        int index = (pageIndex-1)*limitNu;
        String sql = "SELECT * FROM book,bookcase WHERE book.bookcaseid = bookcase.id LIMIT "+index+","+limitNu+";";
        return getAll(sql);
    }

    @Override
    public int getBooks(){
        String sql = "SELECT * FROM book,bookcase WHERE book.bookcaseid = bookcase.id;";
        return getAll(sql).size();
    }

    public List<Book> getAll(String sql){
        //连接数据库获取数据
        Connection connection = JDBCTools.getConnection();
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<Book> bookList = new ArrayList<Book>();
        try {
            preparedStatement = connection.prepareStatement(sql);
            //根据页数进行翻页，查询每页的数据，index页数，limitNu每页的行数
            resultSet = preparedStatement.executeQuery();
            //封装到Book对象中
            while (resultSet.next()){
//                BookCase bookCase = new BookCase(resultSet.getInt(9),resultSet.getString(10));
//                Book book = new Book(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4),resultSet.getInt(5),resultSet.getDouble(6),bookCase);
//                bookList.add(book);

                //最大程度的节省栈内存的方法，仅开辟堆空间（或将bookCase、book创建循环外）
                //添加到List中返回
                bookList.add(new Book(resultSet.getInt(1),resultSet.getString(2),resultSet.getString(3),resultSet.getString(4),resultSet.getInt(5),resultSet.getDouble(6),(new BookCase(resultSet.getInt(9),resultSet.getString(10)))));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            JDBCTools.release(connection,preparedStatement,resultSet);
        }
        return bookList;
    }

}
